package cn.ustb.controller;
import cn.ustb.entity.User;
import cn.ustb.service.UserService;
import cn.ustb.serviceImpl.UserServiceImpl;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static cn.ustb.util.MD5WithSaltUtil.generateSaltPassword;

/**
 * @author ljy
 */
@WebServlet("/findPasswordServlet")
public class FindPasswordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取请求参数username和idCard
        String username = request.getParameter("username");
        String idCard = request.getParameter("idCard");
        //防止重复提交
        Object token = session.getAttribute("token");
        String tokenVlaue = request.getParameter("token");
        if(token != null && token.equals(tokenVlaue)){
            session.removeAttribute("token");
        }else{
            response.sendRedirect(request.getContextPath() + "/repeatsubmit.jsp");
            return;
        }
        //判断账号和凭据正确性
        if("".equals(username) || "".equals(idCard)){
            String message = "账号和凭据不能为空";
            session.setAttribute("message", message);
        }else{
            //从数据库获取登录账号信息
            UserService userService=new UserServiceImpl();
            User user=userService.getUserName(username);
            if(user != null && (!user.getFindMMproof().equals(idCard))){
                //身份凭据匹配失败后返回登录页面并带回一条信息：输入密码错误，请重新输入
                String message = "账号或凭据不正确，请重新输入";
                session.setAttribute("message", message);
                session.setAttribute("username", username);
            }else{
                //重置密码
                if(user !=null){
                    String newPassword = generateSaltPassword("000000");
                    user.setPassword(newPassword);
                    userService.update(user);
                    session.setAttribute("message", "重置密码为：000000");
                }



            }
        }
        //重定向回到登录页面
        response.sendRedirect("findpassword.jsp");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

}
